package com.medical.standard.controller.export;

import com.medical.standard.service.ExportService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/api/export/procedure")
public class ProcedureExportServlet extends HttpServlet {

    private ExportService exportService;

    @Override
    public void init() throws ServletException {
        this.exportService = new ExportService();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");

        try {
            // 读取JSON请求体
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            String jsonString = sb.toString();

            // 使用手动解析JSON
            Map<String, Object> requestData = parseJsonManually(jsonString);
            Map<String, Object> filtersJson = (Map<String, Object>) requestData.get("filters");
            List<Object> selectedFieldsArray = (List<Object>) requestData.get("selectedFields");

            // 构建筛选条件
            Map<String, Object> filters = new HashMap<>();
            if (filtersJson != null) {
                String standardCode = (String) filtersJson.get("standardCode");
                String projectName = (String) filtersJson.get("projectName");

                if (standardCode != null && !standardCode.trim().isEmpty()) {
                    filters.put("standardCode", standardCode.trim());
                }
                if (projectName != null && !projectName.trim().isEmpty()) {
                    filters.put("projectName", projectName.trim());
                }
            }

            // 构建选择的字段列表
            List<String> selectedFields = new ArrayList<>();
            if (selectedFieldsArray != null && !selectedFieldsArray.isEmpty()) {
                for (Object field : selectedFieldsArray) {
                    if (field != null) {
                        selectedFields.add(field.toString());
                    }
                }
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = new String("操作规程表.xlsx".getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            // 导出表格
            exportService.exportOperationProcedureTable(response, filters, selectedFields);

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"error\": \"导出失败: " + e.getMessage() + "\"}");
        }
    }

    /**
     * 手动解析JSON
     */
    private Map<String, Object> parseJsonManually(String jsonString) {
        Map<String, Object> result = new HashMap<>();

        if (jsonString == null || jsonString.trim().isEmpty()) {
            return result;
        }

        // 移除首尾的大括号和空白字符
        String content = jsonString.trim();
        if (content.startsWith("{") && content.endsWith("}")) {
            content = content.substring(1, content.length() - 1).trim();
        }

        // 处理空对象
        if (content.isEmpty()) {
            return result;
        }

        // 按逗号分割键值对，但要注意处理嵌套对象和数组中的逗号
        List<String> pairs = splitJsonString(content);

        for (String pair : pairs) {
            String[] keyValue = pair.split(":", 2);
            if (keyValue.length == 2) {
                String key = extractString(keyValue[0].trim());
                Object value = parseJsonValue(keyValue[1].trim());
                result.put(key, value);
            }
        }

        return result;
    }

    /**
     * 分割JSON字符串，处理嵌套结构
     */
    private List<String> splitJsonString(String jsonString) {
        List<String> pairs = new ArrayList<>();
        StringBuilder current = new StringBuilder();
        int braceCount = 0;
        int bracketCount = 0;
        boolean inQuotes = false;
        char quoteChar = '"';

        for (int i = 0; i < jsonString.length(); i++) {
            char c = jsonString.charAt(i);

            if ((c == '"' || c == '\'') && (i == 0 || jsonString.charAt(i - 1) != '\\')) {
                inQuotes = !inQuotes;
                quoteChar = c;
            }

            if (!inQuotes) {
                if (c == '{') braceCount++;
                if (c == '}') braceCount--;
                if (c == '[') bracketCount++;
                if (c == ']') bracketCount--;
            }

            if (c == ',' && braceCount == 0 && bracketCount == 0 && !inQuotes) {
                pairs.add(current.toString().trim());
                current = new StringBuilder();
            } else {
                current.append(c);
            }
        }

        if (current.length() > 0) {
            pairs.add(current.toString().trim());
        }

        return pairs;
    }

    /**
     * 解析JSON值（支持字符串、对象、数组）
     */
    private Object parseJsonValue(String jsonValue) {
        if (jsonValue.startsWith("\"") && jsonValue.endsWith("\"")) {
            // 字符串
            return jsonValue.substring(1, jsonValue.length() - 1);
        } else if (jsonValue.startsWith("{") && jsonValue.endsWith("}")) {
            // 对象
            return parseJsonManually(jsonValue);
        } else if (jsonValue.startsWith("[") && jsonValue.endsWith("]")) {
            // 数组
            return parseJsonArray(jsonValue);
        } else if (jsonValue.equals("true") || jsonValue.equals("false")) {
            // 布尔值
            return Boolean.parseBoolean(jsonValue);
        } else if (jsonValue.equals("null")) {
            // null值
            return null;
        } else {
            try {
                // 数字
                if (jsonValue.contains(".")) {
                    return Double.parseDouble(jsonValue);
                } else {
                    return Long.parseLong(jsonValue);
                }
            } catch (NumberFormatException e) {
                // 无法解析，返回原字符串
                return jsonValue;
            }
        }
    }

    /**
     * 解析JSON数组
     */
    private List<Object> parseJsonArray(String jsonArray) {
        List<Object> result = new ArrayList<>();

        // 移除首尾的中括号
        String content = jsonArray.substring(1, jsonArray.length() - 1).trim();

        if (content.isEmpty()) {
            return result;
        }

        // 分割数组元素
        List<String> elements = splitJsonString(content);
        for (String element : elements) {
            result.add(parseJsonValue(element.trim()));
        }

        return result;
    }

    /**
     * 从JSON字符串中提取实际字符串值
     */
    private String extractString(String jsonValue) {
        if (jsonValue.startsWith("\"") && jsonValue.endsWith("\"")) {
            return jsonValue.substring(1, jsonValue.length() - 1);
        }
        return jsonValue;
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 返回可导出的字段列表
        response.setContentType("application/json;charset=UTF-8");
        String fieldsJson = "{" +
                "\"standardCode\": \"标准编号\"," +
                "\"standardName\": \"标准名称\"," +
                "\"projectNum\": \"项目条款\"," +
                "\"projectName\": \"项目名称\"," +
                "\"projectRequirement\": \"项目要求\"," +
                "\"equipment\": \"使用设备\"," +
                "\"itemMethod\": \"项目方法\"," +
                "\"note\": \"注意事项\"" +
                "}";
        response.getWriter().write(fieldsJson);
    }
}
